package com.mygenostics.backing;

import static com.mygenostics.constants.SessionConstants.CURRENT_USER;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;

import com.mygenostics.dao.UserDAO;
import com.mygenostics.misc.Util;
import com.mygenostics.misc.WebUtil;
import com.mygenostics.persistence.UserBean;

public class LoginBacking {
	private static Logger log = Logger.getLogger(LoginBacking.class);
	
	private String userName;
	
	private String password;
	
	private String firstName;
	
	private String lastName;
	
	private String email;
	
	public String doLogin() {
		FacesContext context = FacesContext.getCurrentInstance();
		
		boolean authenUser = false;
		
		UserDAO userDao = new UserDAO(); 
		
		UserBean user = userDao.getUserByName(userName);
		
		if (user != null) {
			if (Util.encryptStrBySha(password).equals(user.getPassword())) {
				authenUser = true;
				WebUtil.getSessionMap().put(CURRENT_USER, user);
			}
		}
		
		if (!authenUser) {
			FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login Failed", "Invalid user name or password");
			context.addMessage(null, fm);
            return "failed";
		}
		
		if (log.isInfoEnabled()) {
			log.info("Login success for user " + user.getUserName());
		}
		
		return "success";
	}
	
	public String doRegister() {
		
		UserDAO userDao = new UserDAO();
		
		UserBean user = new UserBean();
		user.setUserName(userName);
		user.setPassword(Util.encryptStrBySha(password));
		user.setFirstName(firstName);
		user.setLastName(lastName);
		user.setEmail(email);
		
		userDao.createUser(user);
		
		return "success";
	}
	
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}
